package com.cssw.fyzb.busi.api.system;

import com.cssw.fyzb.busi.cache.Cache;
import com.cssw.fyzb.busi.cache.CacheKeys;
import com.cssw.fyzb.busi.cache.Fetcher;
import com.cssw.fyzb.busi.convert.Converter;
import com.cssw.fyzb.core.model.vo.system.ParamVo;
import com.cssw.fyzb.busi.service.system.SysParamService;
import com.cssw.fyzb.core.model.dodb.SysParam;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Feng Chen
 */
@Function(description = "根据名字获取系统参数",
        parameters = {
                @Parameter(name = "name", type = Type.String, description = "参数名称", required = true),
                @Parameter(name = "force", type = Type.Boolean, description = "强制刷新缓存，true - 是, false - 否", required = false),
        },
        result = @Result(
                properties = {
                        @Property(name = "name", type = Type.String, description = "参数名"),
                        @Property(name = "value", type = Type.String, description = "参数值"),

                }
        ))
@Component
public class GetParam implements Action {

    @Autowired
    private SysParamService sysParamService;

    private static final Logger logger = LoggerFactory.getLogger(GetParam.class);

    @Override
    public Response execute(Request request) throws Exception {
        String name = request.getString("name");
        Boolean force = request.getBoolean("force");
        try {
            SysParam sysParam = null;
            try {
                // 获取参数
                sysParam = Cache.get(CacheKeys.paramKey(name), new Fetcher<SysParam>() {
                    @Override
                    public SysParam fetch() {
                        return sysParamService.findByCode(name);
                    }
                }, force);
            } catch (Exception e){
                Cache.remove(CacheKeys.paramKey(name));
                sysParam = Cache.get(CacheKeys.paramKey(name), new Fetcher<SysParam>() {
                    @Override
                    public SysParam fetch() {
                        return sysParamService.findByCode(name);
                    }
                }, force);
            }

            // 转换参数
            ParamVo data = ((Converter<SysParam, ParamVo>) p -> {
                ParamVo vo = null;
                if (p != null) {
                    vo = new ParamVo();
                    vo.setName(p.getParamName());
                    vo.setValue(p.getParamValue());
                }
                return vo;
            }).convert(sysParam);

            return Response.success().put("data", data);
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail("操作异常");
        }
    }

}
